<template>
  <div class="user-management-container">
    <el-card class="search-card">
      <div class="search-header">
        <h2>用户管理</h2>
        <el-button type="primary" @click="handleAddUser">添加用户</el-button>
      </div>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入真实姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable style="width: 120px;">
            <el-option v-for="(label, value) in roleOptions" :key="value" :label="label" :value="value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="list-card">
      <el-table :data="userList" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="realName" label="真实姓名" min-width="120"></el-table-column>
        <el-table-column label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">{{ roleOptions[scope.row.role] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="180"></el-table-column>
        <el-table-column label="操作" fixed="right" width="220" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-dropdown @command="(command) => handleRoleChange(scope.row, command)" trigger="click">
                <el-button type="warning" size="small">
                  修改角色
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item 
                      v-for="(label, value) in roleOptions" 
                      :key="value" 
                      :command="value"
                      :disabled="scope.row.role === value"
                    >
                      {{ label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'" 
      v-model="dialogVisible" 
      width="500px"
    >
      <el-form 
        :model="userForm" 
        :rules="userRules" 
        ref="userFormRef" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="dialogType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option v-for="(label, value) in roleOptions" :key="value" :label="label" :value="value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import axios from 'axios'

// 角色选项 - 修改为只有管理员和教师两种角色
const roleOptions = {
  'admin': '管理员',
  'teacher': '教师'
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    'admin': 'danger',
    'teacher': 'success'
  }
  return typeMap[role] || 'info'
}

// 搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  role: ''
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const userFormRef = ref(null)
const submitLoading = ref(false)

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  realName: '',
  role: 'teacher',
  createdAt: null
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await axios.post('http://localhost:8081/api/user/list', searchForm)
    if (response.data.code === 200) {
      userList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    ElMessage.error('获取用户列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = () => {
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchUserList()
}

// 添加用户
const handleAddUser = () => {
  dialogType.value = 'add'
  resetUserForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetUserForm()
  
  // 填充表单数据
  Object.keys(userForm).forEach(key => {
    if (key in row) {
      userForm[key] = row[key]
    }
  })
  
  dialogVisible.value = true
}

// 修改用户角色
const handleRoleChange = async (user, newRole) => {
  if (user.role === newRole) return
  
  try {
    ElMessageBox.confirm(
      `确定要将用户 "${user.realName}" 的角色从 "${roleOptions[user.role]}" 修改为 "${roleOptions[newRole]}" 吗？`,
      '修改角色',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      const updateData = { ...user, role: newRole }
      const response = await axios.post('http://localhost:8081/api/user/update', updateData)
      
      if (response.data.code === 200) {
        ElMessage.success('角色修改成功')
        fetchUserList() // 刷新列表
      } else {
        ElMessage.error(response.data.msg || '角色修改失败')
      }
    }).catch(() => {
      // 用户取消操作
    })
  } catch (error) {
    console.error('修改角色错误:', error)
    ElMessage.error('修改角色失败，请检查网络连接')
  }
}

// 重置用户表单
const resetUserForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  
  userForm.id = null
  userForm.username = ''
  userForm.password = ''
  userForm.realName = ''
  userForm.role = 'teacher'
  userForm.createdAt = null
}

// 提交用户表单
const submitUserForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8081/api/user/add' 
          : 'http://localhost:8081/api/user/update'
        
        const response = await axios.post(url, userForm)
        
        if (response.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加用户成功' : '编辑用户成功')
          dialogVisible.value = false
          fetchUserList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加用户失败' : '编辑用户失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加用户错误:' : '编辑用户错误:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加用户失败，请检查网络连接' : '编辑用户失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-top: 15px;
}

.list-card {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 添加操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: space-around;
  gap: 10px;
}

/* 美化表格样式 */
:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}
</style>